/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.manager;

import br.com.foxline.enums.TypeDocument;
import br.com.foxline.enums.TypeTitleDocument;
import br.com.foxline.model.ActCep;
import br.com.foxline.model.Charter;
import br.com.foxline.model.City;
import br.com.foxline.model.Country;
import br.com.foxline.model.NatureWriting;
import br.com.foxline.model.Part;
import br.com.foxline.model.People;
import br.com.foxline.model.Quality;
import br.com.foxline.model.TitleDocument;
import br.com.foxline.service.ActCepService;
import br.com.foxline.service.CharterService;
import br.com.foxline.service.CityService;
import br.com.foxline.service.CountryService;
import br.com.foxline.service.NatureWritingService;
import br.com.foxline.service.PeopleService;
import br.com.foxline.service.QualityService;
import br.com.foxline.service.TitleDocumentService;
import br.com.foxline.util.Caracter;
import br.com.foxline.util.Msg;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author ely
 */
@ManagedBean
@ViewScoped
public class ManagerReadFileTitDoc {

    @EJB
    TitleDocumentService titleDocumentService;
    @EJB
    CityService cityService;
    @EJB
    CharterService charterService;
    @EJB
    CountryService countryService;
    @EJB
    ActCepService actCepService;
    @EJB
    NatureWritingService natureWritingService;
    @EJB
    PeopleService peopleService;
    @EJB
    QualityService qualityService;
    //private Charter charter;
    private TitleDocument titDoc;
    private Country country;
    private City city;
    private ActCep act, actCep;
    private Part partApresentante, partInteressado, partInteressado2;
    private People apresentante, interessado, interessado2;
    private List<Part> parts;
    private Quality qualityApresentante, qualityInteressado, qualityInteressado2;

    private UploadedFile file;

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }
    
    
    
    
    @PostConstruct 
    public void init() {
        titDoc = new TitleDocument();
        partApresentante = new Part();
        partInteressado = new Part();
        partInteressado2 = new Part();
        apresentante = new People();
        interessado = new People();
        interessado2 = new People();
        parts = new ArrayList<Part>();

 
    }

    public void read(InputStream arquivo) {
        String l = null; 

        try {

            //FileReader reader = new FileReader("/Users/ely/Documents/TitDoc1.txt"); 
            InputStreamReader reader = new InputStreamReader(arquivo);
            BufferedReader read = new BufferedReader(reader);

            StringTokenizer st = null;

            String reg;
            String pro;
            String lpro;
            String datelp;
            String liv;
            String fls;
            String datet;
            String apr; // apresentante
            String inte;// interessado
            String inte2; // interessado 2
            String ob1;
            String ob2;
            String ob3;
            String ob4;
            String ob5;
            String co1; // Observacao
            String co2;
            String co3;
            String co4;
            String co5;

            while ((l = read.readLine()) != null) {

                st = new StringTokenizer(l, ";");
                String dados = null;


                while (st.hasMoreTokens()) {

                    dados = st.nextToken();
                    reg = dados;
 
                    dados = st.nextToken();
                    pro = dados;

                    dados = st.nextToken();
                    lpro = dados;

                    dados = st.nextToken();
                    datelp = dados;
 
                    dados = st.nextToken();
                    liv = dados;

                    dados = st.nextToken();
                    fls = dados;

                    dados = st.nextToken();
                    datet = dados;

                    dados = st.nextToken();
                    apr = dados;

                    dados = st.nextToken();
                    inte = dados;

                    dados = st.nextToken();
                    inte2 = dados;

                    dados = st.nextToken();
                    ob1 = dados;

                    dados = st.nextToken();
                    ob2 = dados;

                    dados = st.nextToken();
                    ob3 = dados;


                    dados = st.nextToken();
                    ob4 = dados;

                    dados = st.nextToken();
                    co1 = dados;

                    dados = st.nextToken();
                    co2 = dados;

                    dados = st.nextToken();
                    co3 = dados;

                    dados = st.nextToken();
                    co4 = dados;

                    dados = st.nextToken();
                    co5 = dados;
 

 
                    // Jogando Valores  

                    String num = liv.replaceAll("\\D*", "");
                    String let = liv.replaceAll("\\d*", "");

                    String numF = fls.replaceAll("\\D*", "");
                    String letF = fls.replaceAll("\\d*", "");

                    
                    titDoc.setTypeTitleDocument(TypeTitleDocument.EFEITO_CONSERVACAO);
                    titDoc.setBook(num);
                    titDoc.setBookComp(Caracter.removecaracter(let));

                    titDoc.setLeaf(numF);
                    titDoc.setLeafComp(Caracter.removecaracter(letF));

                    titDoc.setDatebp(converterData(datelp));

                    titDoc.setRegister(reg);

                    titDoc.setObj(Caracter.removecaracter(ob1 + ob2 + ob3 + ob4));
                    titDoc.setProtocolo(pro);
                    titDoc.setObs(Caracter.removecaracter(co1 + co2 + co3 + co4 + co5));
                    titDoc.setDatetdoc(converterData(datet));

//                    city = cityService.find(3493L);
//                    titDoc.setCity(city);
//
//                    country = countryService.find(18L);
//                    charter.setUf(country);

                    //actCep = actCepService.findActCod("1");



                    apresentante.setName(apr);
                    qualityApresentante = qualityService.findQualityCod("20");

                    interessado.setName(Caracter.removecaracter(inte));
                    qualityInteressado = qualityService.findQualityCod("21");

                    interessado2.setName(Caracter.removecaracter(inte2));
                    qualityInteressado2 = qualityService.findQualityCod("21");


                    partApresentante.setPeople(apresentante);
                    partApresentante.setPartQuality(qualityApresentante);

                    partInteressado.setPeople(interessado);
                    partInteressado.setPartQuality(qualityInteressado);

                    partInteressado2.setPeople(interessado2);
                    partInteressado2.setPartQuality(qualityInteressado2);

                    if (interessado2.getName().equals("") || interessado.getName() == null) {
                        parts.add(partApresentante);
                        parts.add(partInteressado);
                        titDoc.setParts(parts); 

                        titleDocumentService.update(titDoc);
                        apresentante = new People();
                        titDoc = new TitleDocument(); 
                        partApresentante = new Part();
                        interessado = new People();
                        partInteressado = new Part();
                        interessado2 = new People();
                        partInteressado2 = new Part();
                        parts = new ArrayList<Part>();
                    } else if (interessado.getName().equals("") || interessado2.getName() == null) {
                        parts.add(partApresentante);
                        parts.add(partInteressado2);
                        titDoc.setParts(parts);


                        titleDocumentService.update(titDoc);
                        apresentante = new People();
                        titDoc = new TitleDocument();
                        partApresentante = new Part();
                        interessado = new People();
                        partInteressado = new Part();
                        interessado2 = new People();
                        partInteressado2 = new Part();
                        parts = new ArrayList<Part>();

                    }else{ 
                        
                        parts.add(partApresentante);
                        parts.add(partInteressado);
                        parts.add(partInteressado2);
                        titDoc.setParts(parts);


                        titleDocumentService.update(titDoc);
                        apresentante = new People();
                        titDoc = new TitleDocument();
                        partApresentante = new Part();
                        interessado = new People();
                        partInteressado = new Part();
                        interessado2 = new People();
                        partInteressado2 = new Part();
                        parts = new ArrayList<Part>();

                        
                    }


                }




            }

            read.close();
            reader.close();

        } catch (Exception erro) {
            erro.printStackTrace();
            System.err.println(erro);
        }
    }

    public Date converterData(String data) {
        if (data == null || data.equals("") || data.equals(".")) {
            return null;
        }

        Date date = null;
        try {
            DateFormat formater = new SimpleDateFormat("dd/MM/yyyy");
            date = (Date) formater.parse(data);





        } catch (ParseException ex) {
            Logger.getLogger(ManagerReadFile.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        return date;
    } 
    
    public void upload() throws IOException {
        String namefile = "";
       
        
        if(file != null){
            namefile = file.getFileName();
        }
       

        FacesContext facesContext = FacesContext.getCurrentInstance();
        ServletContext scontext = (ServletContext) facesContext.getExternalContext().getContext();
        
        String caminho = scontext.getRealPath(""+namefile);
        
        caminho = "/opt/glassfish3/glassfish/";
        
        System.out.println("caminho "+ caminho);
        if(file != null){
            read(file.getInputstream());
        }
        
        
    }
    
    


}
